package com.lambkit.plugin.druid;

import com.alibaba.druid.pool.DruidDataSource;
import com.jfinal.kit.LogKit;
import com.jfinal.plugin.druid.DruidPlugin;
import com.lambkit.db.DataSourcePlugin;

import javax.sql.DataSource;

public class DruidDataSourcePlugin extends DataSourcePlugin {

	private DruidPlugin druidPlugin;
	private long lastExecuteCount = 0;
	private long lastTime = 0;
	
	public DruidDataSourcePlugin(String configName, DruidPlugin druidPlugin) {
		super(configName);
		this.druidPlugin = druidPlugin;
	}
	
	@Override
	public boolean start() {
		if(druidPlugin!=null) {
			if (druidPlugin.start() == false) {
				String message = "Plugin start error: " + druidPlugin.getClass().getName();
				throw new RuntimeException(message);
			}
		}
		startArp();
		return true;
	}

	@Override
	public boolean stop() {
		stopArp();
		if(druidPlugin!=null) {
			boolean success = false;
			try {
				success = druidPlugin.stop();
			} 
			catch (Exception e) {
				success = false;
				LogKit.error(e.getMessage(), e);
			}
			if (!success) {
				System.err.println("Plugin stop error: " + druidPlugin.getClass().getName());
			}
		}
		return true;
	}

	@Override
	public int getDataSourceActiveState() {
		if(druidPlugin==null || getArp()==null) {
			return 0;
		}
		DruidDataSource ds = (DruidDataSource) druidPlugin.getDataSource();
		long executeCount = ds.getExecuteCount();
		if(lastTime==0) {
			lastExecuteCount = executeCount;
			lastTime = System.currentTimeMillis();
		} else {
			if(lastExecuteCount==executeCount) {
				long currentTime = System.currentTimeMillis();
				long dtime = currentTime - lastTime;
				if(dtime > 1000 * 60) {
					return 2;
				}
			}
		}
		return 1;
	}

	@Override
	public DataSource getDataSource() {
		return druidPlugin!=null ? druidPlugin.getDataSource() : null;
	}
	
}
